/**
 * 研究图谱Store
 * 用于管理研究图谱数据的加载、缓存和展示
 */
import {  observable, action  } from 'mobx-miniprogram';
import { standardizeModuleStore } from '../../helpers/store_standardizer.js';
import { Cache } from '../../helpers/index.js';
import baseStore from '../../global/base_store.js';

// 缓存配置
const CACHE_GRAPH_DATA = 'CACHE_GRAPH_DATA_';
const CACHE_TIME = 15 * 60 * 1000; // 15分钟

export const researchStore = observable({
  ...baseStore, // 继承基础Store

  // 图谱数据
  graphData: null,
  nodes: [],
  links: [],
  isReady: false,

  /**
   * 设置图谱数据
   * @param {Object} data 图谱数据
   */
  setGraphData: action(function(data) {
    if (!data) return;
    
    this.graphData = data;
    this.nodes = this._formatNodes(data.nodes || []);
    this.links = this._formatLinks(data.links || []);
    this.isReady = true;
    
    // 缓存图谱数据
    if (data.projectId) {
      const cacheKey = `${CACHE_GRAPH_DATA}${data.projectId}`;
      Cache.set(cacheKey, data, CACHE_TIME);
    }
  }),

  /**
   * 重置图谱数据
   */
  resetGraphData: action(function() {
    this.graphData = null;
    this.nodes = [];
    this.links = [];
    this.isReady = false;
    this.isLoading = false;
    this.error = null;
  }),

  /**
   * 加载图谱数据
   * @param {Object} params 请求参数
   * @param {String} params.projectId 项目ID
   * @param {Boolean} params.showBranch 是否显示分支
   * @param {Boolean} params.showFlow 是否显示流程
   * @param {Boolean} params.forceRefresh 是否强制刷新
   */
  loadGraphData: action(function(params) {
    if (!params || !params.projectId) return;

    this.setLoading(true);
    
    try {
      const { projectId, showBranch, showFlow, forceRefresh } = params;
      
      // 如果不强制刷新，先尝试从缓存加载
      if (!forceRefresh) {
        const cacheKey = `${CACHE_GRAPH_DATA}${projectId}`;
        const cachedData = Cache.get(cacheKey);
        if (cachedData) {
          this.setGraphData(cachedData);
          this.setLoading(false);
          return;
        }
      }
      
      // 调用云函数获取图谱数据
      wx.cloud.callFunction({
        name: 'research',
        data: {
          action: 'getProjectGraph',
          projectId,
          showBranch,
          showFlow
        }
      }).then(res => {
        const result = res.result || {};
        if (result.code === 0 && result.data) {
          // 添加projectId到数据中，方便缓存
          result.data.projectId = projectId;
          
          // 设置图谱数据
          this.setGraphData(result.data);
        } else {
          this.setError(new Error(result.message || '获取图谱数据失败'));
        }
        
        this.setLoading(false);
      }).catch(err => {
        this.setError(err);
        this.setLoading(false);
      });
    } catch (error) {
      this.setError(error);
      this.setLoading(false);
    }
  }),

  /**
   * 格式化节点数据
   * @param {Array} nodes 节点数据
   * @returns {Array} 格式化后的节点数据
   * @private
   */
  _formatNodes: function(nodes) {
    const currentProjectId = this.graphData?.projectId || '';
    
    return nodes.map(node => {
      // 设置节点颜色
      let color = '#2196F3';
      let size = 16;
      let shape = 'circle';
      
      if (node.type === 'root') {
        color = '#F44336';
        size = 20;
      } else if (node.type === 'flow') {
        color = '#4CAF50';
      } else if (node.type === 'branch') {
        color = '#FF9800';
        size = 18;
        shape = 'diamond';
      } else if (node.type === 'branch_flow') {
        color = '#9C27B0';
      }
      
      // 找出当前选中的项目对应节点
      const isCurrent = currentProjectId === node.id || 
        (node.projectId && currentProjectId === node.projectId);
      
      if (isCurrent) {
        color = '#F44336';
        size = 20;
      }
      
      return {
        ...node,
        color,
        size,
        shape,
        isCurrent
      };
    });
  },

  /**
   * 格式化连线数据
   * @param {Array} links 连线数据
   * @returns {Array} 格式化后的连线数据
   * @private
   */
  _formatLinks: function(links) {
    return links.map(link => {
      // 设置连线颜色和样式
      let color = '#2196F3';
      let style = 'solid';
      let width = 1;
      
      if (link.type === 'normal') {
        color = '#4CAF50';
      } else if (link.type === 'rollback') {
        color = '#F44336';
        style = 'dashed';
      } else if (link.type === 'branch') {
        color = '#FF9800';
        width = 2;
      } else if (link.type === 'merge') {
        color = '#9C27B0';
        style = 'dot';
        width = 2;
      }
      
      return {
        ...link,
        color,
        style,
        width
      };
    });
  },

  /**
   * 重置Store数据
   */
  reset: action(function() {
    this.resetGraphData();
  })
}); 

// 应用标准化Store，确保拥有所有必要的方法和错误处理
export default standardizeModuleStore(researchStore, 'research', 'researchStore');